//
//  TJTextView.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/19.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class TJTextView: UITextView {
    
    // 占位文本的内容.
    var placeholder:String? {
    
        didSet {
            
            placeholderLabel.text = placeholder
        }
    }
    
    // 覆盖父类的属性.-->占位文本的字体大小.
    override var font:UIFont? {
        
        didSet{
            placeholderLabel.font = font
        }
    }
    
    // textView的字体内容.-->属性监听器监听不到,只能用textView的代理方法来监听.
    override var text:String? {
    
        didSet {
        
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangeText"), name: UITextViewTextDidChangeNotification, object: self)
    }
    // 注销通知.
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 通知监听方法.
    @objc private func didChangeText() {
        // 判断有没有文字
        placeholderLabel.hidden = hasText()
    }

    private func setupUI () {
    
        // 设置代理.-->会被控制器的代理覆盖<代理只能一对一>
//        self.delegate = self
        
        // 添加占位文本label
        addSubview(placeholderLabel)
        
        // 添加约束.
        // 去除Autoresizeing
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
    }
  
    // MARK: - 懒加载
    /// 占位label
    private lazy var placeholderLabel: UILabel = {
        // 添加占位label
        let label = UILabel()
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        
        label.text = "分享新鲜事..."
        label.sizeToFit()
        
        return label
    }()
}

//// TextVeiw的代理方法.
//extension TJTextView:UITextViewDelegate {
//
//    func textViewDidChange(textView: UITextView) {
//        placeholderLabel.hidden = true
//    }
//}

